package com.jd.webapp.portal.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jd.common.convention.TTResult;
import com.jd.webapp.portal.pojo.CartItem;
import com.jd.webapp.portal.service.CartService;


@Controller
public class CartController {
	@Autowired
	private CartService cartService;
	
	@RequestMapping("/cart/add/{id}")
	public String cartAdd(@PathVariable long id,@RequestParam(defaultValue="1") int num,
			HttpServletRequest request,HttpServletResponse response){
		try {
			cartService.addCart(id, num, request, response);
			return "cartSuccess";
		} catch (Exception e) {
			e.printStackTrace();
			return "error/exception";
		}
	}
	
	@RequestMapping("/cart/cart")
	public String cartList(HttpServletRequest request,Model model){
		try {
			List<CartItem> carts = cartService.getList(request);
			model.addAttribute("cartList", carts);
			return "cart";
		} catch (Exception e) {
			e.printStackTrace();
			return "error/exception";
		}
	}
	
	@RequestMapping(value="/cart/update/num/{id}/{num}")
	public @ResponseBody Object cartUpdate(@PathVariable long id,@PathVariable int num,HttpServletRequest request,HttpServletResponse response){
		try {
			cartService.updateCart(id, num, request, response);
			return "ok";
		} catch (Exception e) {
			e.printStackTrace();
			return TTResult.fail();
		}
	}
	
	@RequestMapping(value="/cart/delete/{id}")
	public String cartDelete(@PathVariable long id,HttpServletRequest request,HttpServletResponse response){
		try {
			cartService.deleteCart(id, request, response);
			return "redirect:/cart/cart.html";
		} catch (Exception e) {
			e.printStackTrace();
			return "error/exception";
		}
	}
}
